<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="`${
      !isEdit ? '新增查勘案件' : '修改查勘案件 - ' + formData.case_number
    }`"
    :visible="visible"
    :before-close="onClose"
    :style="{ 'max-height': '100vh' }"
  >
    <!-- <div style="max-height: 70vh; overflow-y: auto; padding: 0 30px"> -->
      <el-form
        style="padding: 0 30px"
        ref="form"
        label-width="120px"
        :model="form"
        :rules="rules"
      >
      <el-row>
        <el-col :span="12">
          <el-form-item label="案件号" prop="case_number">
          <el-input
            placeholder="请输入案件号"
            v-model="form.case_number"
          ></el-input>
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户全称" prop="company_name">
          <el-select
            clearable
            placeholder="请选择客户全称"
            v-model="form.company_name"
          >
            <el-option
              v-for="(e, i) in companyOptions"
              :key="i"
              :value="e.label"
              :label="e.label"
            />
          </el-select>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="事故地" prop="address_code">
          <el-cascader
            v-model="form.address_code"
            placeholder="请选择省市区"
            :options="options"
            ref="classifyRef"
            @change="handleChange"
          />
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="accident_address">
          <el-input
            placeholder="请输入详细地址"
            v-model="form.accident_address"
          ></el-input>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="案件类型" prop="case_type">
          <el-select clearable v-model="form.case_type">
            <el-option
              v-for="(e, i) in oilList"
              :key="i"
              :value="e.value"
              :label="e.label"
            />
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车牌号" prop="car_number">
          <el-input
            placeholder="请输入车牌号"
            v-model="form.car_number"
          ></el-input>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="接单时间" prop="receiving_time">
          <el-date-picker
            v-model="form.receiving_time"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="查勘员" prop="surveyer">
            <el-input
              placeholder="请输入查勘员"
              v-model="form.surveyer"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="查勘状态" prop="status" v-if="!showPicture">
          <el-select
            clearable
            placeholder="请选择查勘状态"
            v-model="form.status"
          >
            <el-option
              v-for="(e, i) in surveyStatusOptions"
              :key="i"
              :value="e.value"
              :label="e.label"
            />
          </el-select>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="查勘状态" prop="status" v-if="!showPicture">
          <el-select
            clearable
            placeholder="请选择查勘状态"
            v-model="form.status"
          >
            <el-option
              v-for="(e, i) in surveyStatusOptions"
              :key="i"
              :value="e.value"
              :label="e.label"
            />
          </el-select>
        </el-form-item>
        </el-col> -->
      </el-row>
      <el-form-item label="现场照片" prop="picture" v-if="showPicture">
          <!-- <el-button style="marginRight:10px;" @click="getFileName" size="mini" type="success">选择文件</el-button>
        <input type="file" multiple="multiple" id="minIoFile" ref="minIoFile" v-show="false" @change="getFile">
        <el-button v-if="fileList.length>0" style="marginRight:10px;" @click="upload" size="mini" type="success">上传</el-button>
        <ul class="uploadFileList">
          <li v-for="(item, index) in fileList" :key="index">
           <span class="subString">{{ item.name }}</span>&nbsp;
           <span>({{ (item.size / 1024 / 1024).toFixed(5) }}M)</span>
           <div class="floatRight" style="float: right;">
            <i class="el-icon-close" style="cursor: pointer;" @click="deleteMinioFile(index)"></i>
           </div>
          </li>
        </ul> -->
          <!-- <ul>
         <li v-for="(item, index) in urlList" :key="index">
           <span @click="downLoad(item.url, item.name)">{{ item.name }}-----</span>
         </li>
        </ul> -->
        <el-upload
              class="load"
              action="#"
              :on-preview="handlePreview"
              :http-request="uploadImage"
              :on-change="handleChangeImg"
              :on-remove="handleRemove"
              :show-file-list="false"
              :file-list="fileList"
              multiple
              style="margin-left: 5px"
            >
              <el-button type="primary" size="mini">上传</el-button>
            </el-upload>
            <div
              v-for="(item, index) in imgArr"
              :key="index"
              style="position: relative;display: inline-block;margin-top: 10px;"
            >
              <el-image
                :src="item"
                :preview-src-list="getImgList(imgArr,index)"
                style="width: 80px; height: 80px; margin: 0 0 5px 5px"
              ></el-image>
              <i
                class="el-icon-circle-close"
                @click="removeImage(index)"
                style="position: absolute;
                  top: 0;
                  right: 0;
                  cursor: pointer;
                  background-color:#fff;
                  padding: 2px;
                "
              ></i>
            </div>
          <!-- <el-upload
            action="#"
            :http-request="uploadImage"
            :on-change="handleChangeImg"
            list-type="picture-card"
            :file-list="fileList"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog> -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="footer">
        <el-button @click="onClose">取 消</el-button>
        <el-button type="primary" @click="onEnter">提 交</el-button>
      </div>
    <!-- </div> -->
  </el-dialog>
</template>

<script>
import { regionData } from "element-china-area-data";
import { surveyorList } from "@/api/system/caseManage";
import { uploadImage, removeObject } from "@/utils/minio";
// import { Client } from "minio";
// import stream from "stream";
export default {
  name: "caseEdit",
  components: {},
  data() {
    return {
      options: regionData,
      showPicture: true,
      areaNames: [],
      imgArr: [],
      companyOptions: [
        {
          label: "中国平安财产保险股份有限公司",
          value: 1,
        },
        {
          label: "中国人民财产保险公司",
          value: 2,
        },
        {
          label: "国元农业保险股份有限公司",
          value: 3,
        },
      ],
      customerOptions: [
        {
          label: "张明",
          value: 1,
        },
        {
          label: "李森",
          value: 2,
        },
      ],
      oilList: [
        {
          label: "工程机械类",
          value: 1,
        },
        {
          label: "运输工具类",
          value: 2,
        },
      ],
      surveyStatusOptions: [
        {
          label: "正在查勘",
          value: 1,
        },
        {
          label: "已查勘待审核",
          value: 2,
        },
        {
          label: "已查勘审核通过",
          value: 3,
        },
      ],
      form: {},
      rules: {
        case_number: [{ required: true, message: "必需", trigger: ["blur"] }],
        company_name: [{ required: true, message: "必需", trigger: ["blur"] }],
        address_code: [{ required: true, message: "必需", trigger: ["blur"] }],
        accident_address: [
          { required: true, message: "必需", trigger: ["blur"] },
        ],
        case_type: [{ required: true, message: "必需", trigger: ["blur"] }],
        car_number: [{ required: true, message: "必需", trigger: ["blur"] }],
        surveyer: [{ required: true, message: "必需", trigger: ["blur"] }],
        status: [{ required: true, message: "必需", trigger: ["blur"] }],
        // picture: [{ required: true, message: "必需", trigger: ["change"] }],
      },
      // minioClient: new Client({
      //   endPoint: "47.96.251.237",
      //   port: 9000,
      //   useSSL: false,
      //   accessKey: "ahct",
      //   secretKey: "ahct123456",
      // }),
      // bucketName: "ahctbucket",
      fileName: "",
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default() {
        return {};
      },
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  created() {
  },
  computed: {},
  watch: {
    formData(e) {
      console.log(e, "KKKKKKKKK");
      this.form = {
        ...e,
      };
      this.form.address_code = this.form.address_code.split(",");
    },
    visible(v) {
      v && this.validateReset();
    },
  },
  methods: {
    getImgList(e,index) {
      let arr = [];
      let i = 0;
      for (i; i < e.length; i++) {
        arr.push(e[i + index]);
        if (i + index >= e.length - 1) {
          index = 0 - (i + 1);
        }
      }
      return arr;
    },
    // toBlob(base64Data) {
    //   let byteString = base64Data;
    //   if (base64Data.split(",")[0].indexOf("base64") >= 0) {
    //     byteString = atob(base64Data.split(",")[1]);
    //   } else {
    //     byteString = unescape(base64Data.split(",")[1]);
    //   }
    //   const mimeString = base64Data.split(";")[0].split(":")[1];
    //   const uintArr = new Uint8Array(byteString.length);
    //   for (let i = 0; i < byteString.length; i++) {
    //     uintArr[i] = byteString.charCodeAt(i);
    //   }
    //   return new Blob([uintArr], { type: mimeString });
    // },
    handleChangeImg(file, fileList) {
      // if (fileList.length == 1) {
      //   let { picture, ...data } = this.rules;
      //   this.rules = data;
      // }
      // this.$refs.form.clearValidate("picture");
    },
    uploadImage(request) {
      console.log(request, "1111111111111", this.fileList);
      uploadImage({
        file: request.file,
        onSuccess: (only) => {
          this.fileList.push(only);
          this.imgArr.push(only.url);
          console.log(this.fileList, "CCCCCCCCCCCCcc");
        },
        onError: (err) => {
          console.error("Upload failed", err);
        },
      });
      // const isFileExists = this.fileList.some((uploadedFile) => {
      //   const originalFileName = uploadedFile.name
      //     .split("-")
      //     .slice(1)
      //     .join("-");
      //   return originalFileName === file.name;
      // });
      // if (isFileExists) {
      //   this.$message.error("该文件已上传");
      //   onError("该文件已上传");
      //   return;
      // }
      // const fileName = `${file.uid}-${file.name}`;
      // const mineType = file.type;
      // const fileSize = file.size;
      // const metadata = {
      //   "content-type": mineType,
      //   "content-length": fileSize,
      // };
      // this.minioClient.bucketExists(this.bucketName, (err) => {
      //   if (err) {
      //     if (err.code == "NoSuchBucket") return console.log("bucket不存在");
      //   }
      //   console.log("Bucket存在");
      //   const reader = new FileReader();
      //   reader.readAsDataURL(file);
      //   reader.onloadend = (e) => {
      //     const dataurl = e.target.result;
      //     const blob = this.toBlob(dataurl);
      //     const reader2 = new FileReader();
      //     reader2.readAsArrayBuffer(blob);
      //     reader2.onload = (ex) => {
      //       const bufferStream = new stream.PassThrough();
      //       bufferStream.end(Buffer.from(ex.target.result));
      //       this.minioClient.putObject(
      //         this.bucketName,
      //         fileName,
      //         bufferStream,
      //         fileSize,
      //         metadata,
      //         (err, etag) => {
      //           console.log(etag);
      //           if (err == null) {
      //             this.minioClient.presignedGetObject(
      //               this.bucketName,
      //               fileName,
      //               24 * 60 * 60,
      //               (err, presignedUrl) => {
      //                 if (err) return console.log(err);
      //                 console.log(presignedUrl);
      //                 const only = { url: presignedUrl, name: fileName };
      //                 console.log(only);
      //                 this.fileList.push(only);
      //                 this.imgArr.push(only.url);
      //                 console.log(this.fileList, "CCCCCCCCCCCCcc");
      //               }
      //             );
      //           }
      //         }
      //       );
      //     };
      //   };
      // });
    },
    handlePreview(file) {
      // this.dialogImageUrl = file.url;
      // this.dialogVisible = true;
    },
    removeImage(index) {
      const file = this.fileList[index];
      const fileName = file.name;
      this.imgArr.splice(index, 1);
      this.fileList.splice(index, 1);
      removeObject(fileName, () => {
        console.log("对象已成功删除");
      }, (err) => {
        console.error("删除对象时出错：", err);
      });
      // this.minioClient.removeObject(this.bucketName, fileName, (err) => {
      //   if (err) {
      //     console.error("删除对象时出错：", err);
      //   } else {
      //     console.log("对象已成功删除", this.bucketName, fileName);
      //   }
      // });
      // if (this.imgArr.length == 0) {
      //   this.rules.picture = [
      //     { required: true, message: "必需", trigger: "change" },
      //   ];
      // }
    },
    handleRemove(file, fileList) {
      // const fileName = file.name;
      // this.minioClient.removeObject(this.bucketName, fileName, (err) => {
      //   if (err) {
      //     console.error("删除对象时出错：", err);
      //   } else {
      //     console.log("对象已成功删除", this.bucketName, fileName);
      //   }
      // });
      // const index = this.fileList.findIndex((item) => item.name === fileName);
      // if (index !== -1) {
      //   this.fileList.splice(index, 1);
      // }
      // if (fileList.length == 0) {
      //   this.rules.picture = [
      //     { required: true, message: "必需", trigger: "change" },
      //   ];
      // }
      // console.log(file, fileList, this.fileList);
    },
    handleChange(e) {
      if(e) {
        this.areaNames = e
        .map((code) => this.findAreaByCode(code, this.options)?.label)
        .filter(Boolean);
      }
      console.log(e, this.areaNames);
    },
    findAreaByCode(code, options) {
      const found = options.find((option) => option.value === code);
      if (found) return found;
      for (const option of options) {
        if (option.children) {
          const childFound = this.findAreaByCode(code, option.children);
          if (childFound) return childFound;
        }
      }
      return null;
    },
    validateReset() {
      this.$refs.form && this.$refs.form.clearValidate();
    },
    onClose() {
      this.removeUploadedFiles();
      this.$emit("onClose");
    },
    removeUploadedFiles() {
      this.fileList.forEach((file) => {
        const fileName = file.name;
        this.minioClient.removeObject(this.bucketName, fileName, (err) => {
          if (err) {
            console.error("删除对象时出错：", err);
          } else {
            console.log("对象已成功删除", this.bucketName, fileName);
          }
        });
      });
      this.fileList = [];
    },
    onEnter() {
      // const formattedReceivingTime = this.form.receiving_time
      //   ? new Date(this.form.receiving_time)
      //       .toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })
      //       .replace(/\//g, "-")
      //   : "";
      const imgList = this.fileList.map((item) => item.url.split('?')[0]);
      this.$refs.form.validate((res) => {
        let params = {
          id: this.form.id,
          case_number: this.form.case_number,
          company_name: this.form.company_name,
          province: this.areaNames[0],
          city: this.areaNames[1],
          area: this.areaNames[2],
          accident_address: this.form.accident_address,
          address_code: this.form.address_code,
          case_type: this.form.case_type,
          car_number: this.form.car_number,
          // receiving_time: formattedReceivingTime,
          surveyer: this.form.surveyer,
          status: this.form.status,
          imgList: imgList,
        };
        if (!this.form.id) {
          delete params.id;
        } else {
          delete params.imgList;
        }
        if (res) {
          this.$emit("onEnter", params);
        }
      });
    },
  },
};
</script>

<style scoped>
.footer {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
